<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed, h } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import {
  ElMessage,
  ElCard,
  ElButton,
  ElSelect,
  ElOption,
  ElProgress,
} from "element-plus";
import { Refresh, Download, Document } from "@element-plus/icons-vue";
import * as echarts from "echarts";
import {
  getAnalyticsData,
  exportAnalyticsReport,
  getScoreTemplateList,
} from "../servers";

const loading = ref(false);
const templateList = ref<any[]>([]);
const selectedTemplateId = ref<number | null>(null);
const selectedDays = ref<number>(7);

// 搜索表单数据
const searchFormData = reactive({
  template_id: null as number | null,
  days: 7,
});

// 统计数据
const analyticsData = ref<any>({
  key_metrics: {
    total_assets: 0,
    average_score: 0,
    high_risk_count: 0,
    risk_rate: 0,
  },
  risk_distribution: {
    critical: 0,
    high: 0,
    medium: 0,
    low: 0,
  },
  dimension_contribution: [],
  score_distribution: [],
  risk_change_top10: [],
  risk_trend: [],
});

// 图表引用
const pieChartRef = ref<HTMLDivElement>();
const lineChartRef = ref<HTMLDivElement>();
const barChartRef = ref<HTMLDivElement>();
const histogramRef = ref<HTMLDivElement>();

let pieChart: echarts.ECharts | null = null;
let lineChart: echarts.ECharts | null = null;
let barChart: echarts.ECharts | null = null;
let histogramChart: echarts.ECharts | null = null;

// 表格列配置
const dimensionColumns = ref<TableColumn[]>([
  {
    label: "维度名称",
    prop: "dimension_name",
    minWidth: 150,
    show: true,
  },
  {
    label: "平均扣分",
    prop: "avg_deduction",
    width: 120,
    show: true,
    render: (row) => {
      return `${row.avg_deduction?.toFixed(2) || 0}分`;
    },
  },
  {
    label: "占比",
    prop: "percentage",
    width: 120,
    show: true,
    render: (row) => {
      return `${row.percentage?.toFixed(1) || 0}%`;
    },
  },
  {
    label: "资产数",
    prop: "asset_count",
    width: 100,
    show: true,
  },
  {
    label: "柱状图",
    prop: "chart",
    minWidth: 200,
    show: true,
    render: (row) => {
      const percentage = row.percentage || 0;
      return h("div", [
        h(ElProgress, {
          percentage: percentage,
          color: "#409EFF",
          strokeWidth: 20,
          format: () => "",
        }),
      ]);
    },
  },
]);

const riskChangeColumns = ref<TableColumn[]>([
  {
    label: "资产IP",
    prop: "asset_ip",
    minWidth: 150,
    show: true,
  },
  {
    label: "当前分",
    prop: "current_score",
    width: 100,
    show: true,
    render: (row) => {
      return `${row.current_score?.toFixed(1) || 0}分`;
    },
  },
  {
    label: "上次分",
    prop: "previous_score",
    width: 100,
    show: true,
    render: (row) => {
      return `${row.previous_score?.toFixed(1) || 0}分`;
    },
  },
  {
    label: "变化",
    prop: "score_change",
    width: 120,
    show: true,
    render: (row) => {
      const change = row.score_change || 0;
      const symbol = change > 0 ? "↑" : change < 0 ? "↓" : "→";
      const color =
        change > 0 ? "#67C23A" : change < 0 ? "#F56C6C" : "#909399";
      return h(
        "span",
        { style: { color, fontWeight: "bold" } },
        `${symbol}${Math.abs(change).toFixed(1)}分`
      );
    },
  },
  {
    label: "趋势",
    prop: "trend",
    width: 100,
    show: true,
    render: (row) => {
      const change = row.score_change || 0;
      if (change > 0) {
        return h("span", { style: { color: "#67C23A" } }, "✅ 改善");
      } else if (change < 0) {
        return h("span", { style: { color: "#F56C6C" } }, "⚠️ 恶化");
      } else {
        return h("span", { style: { color: "#909399" } }, "→ 持平");
      }
    },
  },
]);

// 搜索表单配置
const searchFormConfig = computed<FormItemConfig[]>(() => [
  {
    key: "template_id",
    name: "模板",
    type: "select",
    labelWidth: "100px",
    placeholder: "选择模板",
    params: {
      options: [
        { label: "全部模板", value: null },
        ...templateList.value.map((t) => ({
          label: t.label,
          value: t.value,
        })),
      ],
    },
  },
  {
    key: "days",
    name: "时间范围",
    type: "select",
    labelWidth: "100px",
    placeholder: "选择时间范围",
    params: {
      options: [
        { label: "最近7天", value: 7 },
        { label: "最近15天", value: 15 },
        { label: "最近30天", value: 30 },
        { label: "最近60天", value: 60 },
        { label: "最近90天", value: 90 },
      ],
    },
  },
]);

// 初始化饼图
const initPieChart = () => {
  if (!pieChartRef.value) return;
  pieChart = echarts.init(pieChartRef.value);
  const dist = analyticsData.value.risk_distribution || {};
  const total =
    (dist.critical || 0) +
    (dist.high || 0) +
    (dist.medium || 0) +
    (dist.low || 0);
  if (total === 0) return;

  pieChart.setOption({
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)",
    },
    legend: {
      bottom: 0,
      orient: "horizontal",
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: true,
          formatter: "{b}: {d}%",
        },
        data: [
          {
            name: "严重",
            value: dist.critical || 0,
            itemStyle: { color: "#FF4D4F" },
          },
          {
            name: "高危",
            value: dist.high || 0,
            itemStyle: { color: "#FF7A45" },
          },
          {
            name: "中危",
            value: dist.medium || 0,
            itemStyle: { color: "#FFA940" },
          },
          {
            name: "低危",
            value: dist.low || 0,
            itemStyle: { color: "#52C41A" },
          },
        ],
      },
    ],
  });
};

// 初始化折线图
const initLineChart = () => {
  if (!lineChartRef.value) return;
  lineChart = echarts.init(lineChartRef.value);
  const trend = analyticsData.value.risk_trend || [];
  const dates = trend.map((item: any) => item.date);
  const criticalSeries = trend.map((item: any) => item.critical || 0);
  const highSeries = trend.map((item: any) => item.high || 0);
  const mediumSeries = trend.map((item: any) => item.medium || 0);
  const lowSeries = trend.map((item: any) => item.low || 0);

  lineChart.setOption({
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["严重", "高危", "中危", "低危"],
      bottom: 0,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: dates,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "严重",
        type: "line",
        data: criticalSeries,
        itemStyle: { color: "#FF4D4F" },
      },
      {
        name: "高危",
        type: "line",
        data: highSeries,
        itemStyle: { color: "#FF7A45" },
      },
      {
        name: "中危",
        type: "line",
        data: mediumSeries,
        itemStyle: { color: "#FFA940" },
      },
      {
        name: "低危",
        type: "line",
        data: lowSeries,
        itemStyle: { color: "#52C41A" },
      },
    ],
  });
};

// 初始化柱状图（维度贡献）
const initBarChart = () => {
  if (!barChartRef.value) return;
  barChart = echarts.init(barChartRef.value);
  const contribution = analyticsData.value.dimension_contribution || [];
  const names = contribution.map((item: any) => item.dimension_name);
  const values = contribution.map((item: any) => item.avg_deduction || 0);

  barChart.setOption({
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: names,
      axisLabel: {
        rotate: 15,
      },
    },
    yAxis: {
      type: "value",
      name: "平均扣分",
    },
    series: [
      {
        type: "bar",
        data: values,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#83bff6" },
            { offset: 0.5, color: "#188df0" },
            { offset: 1, color: "#188df0" },
          ]),
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c}分",
        },
      },
    ],
  });
};

// 初始化直方图（分数分布）
const initHistogram = () => {
  if (!histogramRef.value) return;
  histogramChart = echarts.init(histogramRef.value);
  const distribution = analyticsData.value.score_distribution || [];
  const ranges = distribution.map((item: any) => item.range);
  const counts = distribution.map((item: any) => item.count || 0);

  histogramChart.setOption({
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: ranges,
      name: "分数段",
    },
    yAxis: {
      type: "value",
      name: "资产数量",
    },
    series: [
      {
        type: "bar",
        data: counts,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#ffd89b" },
            { offset: 1, color: "#19547b" },
          ]),
        },
        label: {
          show: true,
          position: "top",
        },
      },
    ],
  });
};

// 获取统计数据
const fetchAnalyticsData = async () => {
  loading.value = true;
  try {
    const params: any = {
      days: searchFormData.days,
    };
    if (searchFormData.template_id) {
      params.template_id = searchFormData.template_id;
    }
    const { data } = await getAnalyticsData(params);
    analyticsData.value = data || analyticsData.value;

    await nextTick();
    initPieChart();
    initLineChart();
    initBarChart();
    initHistogram();
  } catch (error: any) {
    ElMessage.error(error.message || "获取统计数据失败");
  } finally {
    loading.value = false;
  }
};

// 获取模板列表
const fetchTemplateList = async () => {
  try {
    const { data } = await getScoreTemplateList();
    templateList.value =
      data?.list?.map((item: any) => ({
        label: item.template_name,
        value: item.id,
      })) || [];
  } catch (error: any) {
    ElMessage.error(error.message || "获取模板列表失败");
  }
};

// 搜索
const handleSearch = () => {
  fetchAnalyticsData();
};

// 导出Excel
const handleExportExcel = async () => {
  try {
    await exportAnalyticsReport({
      template_id: searchFormData.template_id || undefined,
      days: searchFormData.days,
      format: "excel",
    });
    ElMessage.success("导出Excel成功");
  } catch (error: any) {
    ElMessage.error(error.message || "导出Excel失败");
  }
};

// 导出PDF
const handleExportPDF = async () => {
  try {
    await exportAnalyticsReport({
      template_id: searchFormData.template_id || undefined,
      days: searchFormData.days,
      format: "pdf",
    });
    ElMessage.success("生成PDF报告成功");
  } catch (error: any) {
    ElMessage.error(error.message || "生成PDF报告失败");
  }
};

onMounted(() => {
  fetchTemplateList();
  fetchAnalyticsData();
});
</script>

<template>
  <div v-loading="loading">
    <!-- 筛选区域 -->
    <el-card shadow="never">
      <div style="display: flex; align-items: center; gap: 16px; flex-wrap: wrap">
        <DynamicForm
          v-model="searchFormData"
          :form-config="searchFormConfig"
          :gutter="16"
          inline
        >
          <template #after>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">刷新</el-button>
              <el-button :icon="Download" @click="handleExportExcel">
                导出Excel
              </el-button>
              <el-button :icon="Document" @click="handleExportPDF">
                生成PDF报告
              </el-button>
            </el-form-item>
          </template>
        </DynamicForm>
      </div>
    </el-card>

    <div style="height: 10px"></div>

    <!-- 关键指标卡片 -->
    <el-card shadow="never">
      <div style="display: flex; gap: 24px; flex-wrap: wrap">
        <div style="flex: 1; min-width: 150px">
          <div style="color: #909399; font-size: 14px; margin-bottom: 8px">
            📊 总资产
          </div>
          <div style="font-size: 24px; font-weight: bold; color: #303133">
            {{ analyticsData.key_metrics?.total_assets || 0 }}
          </div>
        </div>
        <div style="flex: 1; min-width: 150px">
          <div style="color: #909399; font-size: 14px; margin-bottom: 8px">
            📈 平均分
          </div>
          <div style="font-size: 24px; font-weight: bold; color: #409EFF">
            {{ analyticsData.key_metrics?.average_score?.toFixed(1) || 0 }}
          </div>
        </div>
        <div style="flex: 1; min-width: 150px">
          <div style="color: #909399; font-size: 14px; margin-bottom: 8px">
            🔴 高风险
          </div>
          <div style="font-size: 24px; font-weight: bold; color: #F56C6C">
            {{ analyticsData.key_metrics?.high_risk_count || 0 }}
            <span style="font-size: 14px; color: #909399; margin-left: 4px"
              >(↑{{ analyticsData.key_metrics?.high_risk_increase || 0 }})</span
            >
          </div>
        </div>
        <div style="flex: 1; min-width: 150px">
          <div style="color: #909399; font-size: 14px; margin-bottom: 8px">
            📉 风险率
          </div>
          <div style="font-size: 24px; font-weight: bold; color: #E6A23C">
            {{ analyticsData.key_metrics?.risk_rate?.toFixed(1) || 0 }}%
            <span style="font-size: 14px; color: #909399; margin-left: 4px"
              >(↑{{ analyticsData.key_metrics?.risk_rate_increase?.toFixed(1) || 0 }}%)</span
            >
          </div>
        </div>
      </div>
    </el-card>

    <div style="height: 10px"></div>

    <!-- 风险分布图 -->
    <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 12px">
      <el-card shadow="never">
        <template #header>
          <div style="font-weight: 600">风险等级饼图</div>
        </template>
        <div ref="pieChartRef" style="height: 300px"></div>
      </el-card>

      <el-card shadow="never">
        <template #header>
          <div style="font-weight: 600">风险等级趋势（折线图）</div>
        </template>
        <div ref="lineChartRef" style="height: 300px"></div>
      </el-card>
    </div>

    <div style="height: 10px"></div>

    <!-- 维度贡献分析 -->
    <el-card shadow="never">
      <template #header>
        <div style="font-weight: 600">维度贡献分析</div>
      </template>
      <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 16px">
        <div>
          <DynamicTable
            :columns="dimensionColumns"
            :data="analyticsData.dimension_contribution || []"
            :show-pagination="false"
            :show-toolbar="false"
            :border="true"
          />
        </div>
        <div>
          <div ref="barChartRef" style="height: 300px"></div>
        </div>
      </div>
    </el-card>

    <div style="height: 10px"></div>

    <!-- 分数分布直方图 -->
    <el-card shadow="never">
      <template #header>
        <div style="font-weight: 600">分数分布直方图</div>
      </template>
      <div ref="histogramRef" style="height: 350px"></div>
    </el-card>

    <div style="height: 10px"></div>

    <!-- 风险变化TOP10 -->
    <el-card shadow="never">
      <template #header>
        <div style="font-weight: 600">风险变化TOP10</div>
      </template>
      <DynamicTable
        :columns="riskChangeColumns"
        :data="analyticsData.risk_change_top10 || []"
        :show-pagination="false"
        :show-toolbar="false"
        :border="true"
      />
    </el-card>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-card__header) {
  font-weight: 600;
}
</style>
